package com.linkelee.server.aspect;

import com.google.gson.Gson;
import com.linkelee.api.annotation.SysLogSave;
import com.linkelee.api.model.sys.SysLog;
import com.linkelee.api.model.sys.SysUser;
import com.linkelee.api.service.sys.ISysLogService;
import com.linkelee.api.util.HttpContextUtils;
import com.linkelee.api.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 系统日志，切面处理类
 *
 * @author lsl 154751575@qq.com
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {
	@Autowired
	private ISysLogService sysLogService;
	
	@Pointcut("within(@org.springframework.stereotype.Controller *)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;
		//保存日志
		saveAndPrintSysLog(point, time,result);
		return result;
	}

	private void saveAndPrintSysLog(ProceedingJoinPoint joinPoint, long time,Object result) {
		// 方法签名
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		// 方法
		Method method = signature.getMethod();
		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		//请求的参数
		Object[] args = joinPoint.getArgs();
		//输出信息
		List<String> aspectClasses = Stream.of("com.linkelee","java.util","java.lang")
				.collect(Collectors.toList());
		StringBuilder builder = new StringBuilder();
		for(Object arg:args){
			aspectClasses.stream().forEach(aspectClass->{
				if(arg.getClass().getName().indexOf(aspectClass)!=-1){
					builder.append(new Gson().toJson(arg));
				}
			});
		}
		String strMessage = String
				.format("\nclass:%s\n方法:%s 执行时间:%sms\n参数:%s\n返回值:%s",
						className,
						methodName,
						String.valueOf(time),
						builder.toString(),
						new Gson().toJson(result));
		log.info(strMessage);
		SysLog sysLog = new SysLog();
		SysLogSave syslog = method.getAnnotation(SysLogSave.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
			sysLog.setMethod(className + "." + methodName + "()");
			try{
				String params = new Gson().toJson(args);
				sysLog.setParams(params);
			}catch (Exception e){
				log.error(e.getMessage(),e);
			}
			//获取request
			HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
			//设置IP地址
			sysLog.setIp(IPUtils.getIpAddr(request));
			//用户名
			String username = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getUsername();
			sysLog.setUsername(username);
			sysLog.setTime(time);
			sysLog.setCreateDate(new Date());
			//保存系统日志
			sysLogService.save(sysLog);
		}
	}
}
